import requests
from loguru import logger
from requests.adapters import HTTPAdapter

from core import DESAdapter, jdgsSign

sess = requests.session()
sess.mount('https://api.m.jd.com', DESAdapter())
sess.mount('http://', HTTPAdapter(max_retries=3))
sess.mount('https://', HTTPAdapter(max_retries=3))


# sess = requests.session()
## 补全sign算法
def getSign(funid, body, client, ver, uuid, times):
    url = 'http://121.43.58.252:7083/jd/sign'
    body = {
        'funid': funid,
        'body': body,
        'client': client,
        'ver': ver,
        'uuid': uuid,
        'times': times
    }
    sign = requests.post(url=url, json=body).json()
    logger.debug(sign)
    return sign


def getbody(content, flag):
    url = 'http://121.43.58.252:7083/jd/body'
    body = {
        'flag': flag,
        'content': content,
    }
    body_ret = requests.post(url=url, json=body).json()
    logger.debug(body_ret)
    return body_ret


jdgs_url = 'http://121.43.58.252:7083/jd/jdgs'

headers = {
    "Host": "api.m.jd.com",
    "j-e-c": "%7B%22hdid%22%3A%22JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw%3D%22%2C%22ts%22%3A1718960925317%2C%22ridx%22%3A-1%2C%22cipher%22%3A%7B%22pin%22%3A%22c2VybQvrTUU3TUO1TUTL%22%7D%2C%22ciphertype%22%3A5%2C%22version%22%3A%221.2.0%22%2C%22appname%22%3A%22com.jingdong.app.mall%22%7D",
    "x-rp-client": "android_3.0.0",
    "jdgs": "",
    "user-agent": "okhttp/3.12.16;jdmall;android;version/12.3.1;build/99032",
    "x-referer-package": "com.jingdong.app.mall",
    "charset": "UTF-8",
    "x-referer-page": "com.jingdong.app.mall.MainFrameActivity",
    "x-pp-aew": "64",
    "cache-control": "no-cache",
    "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Cookie": 'pin=serlia%E7%A5%BA;wskey=AAJmdUMdAEAyfvagBTZcSvK-XIq1aSbotl9vcD5Kbti8Dr1i2J0IC_nTESUOU2Ju2nD6WJf7wgsAHNLnV36XFpqOzu3FLuPG;whwswswws=JD012145b9a81gioOWaS1718960913203053r5xQcnWw7qizVL_Yd86Qp-AHSdlODYmTNNQd7_wvuVoku2Rg3lVF3V8FiLQYQk5X6-B8_C2kyF0sYHLb0SCqA19ea2gx~BApXcnQQFOfVC9q4Q8kfutLLJaXe7qik49WKI4zZo9xJ1Mkp5aIC2;unionwsws={"devicefinger":"eidA956e812095s7LZ5D7hlMTqaKB5eZ2zAKPi2eRX5YUqf9Grx45MGWtGQyDX6+FPuz01p1JS2KwC5+rDzlGtQ64IdwlsmmgI3oNz+1NAxL9TDaK8E3","jmafinger":"JD012145b9a81gioOWaS1718960913203053r5xQcnWw7qizVL_Yd86Qp-AHSdlODYmTNNQd7_wvuVoku2Rg3lVF3V8FiLQYQk5X6-B8_C2kyF0sYHLb0SCqA19ea2gx~BApXcnQQFOfVC9q4Q8kfutLLJaXe7qik49WKI4zZo9xJ1Mkp5aIC2"}'
}
# cookies = {
#     "pin": "jd_5f537489507a0",
#     "wskey": "AARmF_GdAEBAAGhbHldEgf4rJJw_6U8zTOYySVXOxAJnUmKC1IH3kEWnfuKH8ZR7JmxzN7DBOxMKmsLL6-w9N9KIXqf1cSbP",
#     "whwswswws": "JD012145b9JRG2W4U4Q417187121116600670W-_joxxqQa_R-6v46UFiijYmgl1Iqh5ez_k5PGWQzUuRCq8ohiG9jWJCIqkPL1kL6t-8dWo_11h_A2PNOYtg0tvjldk~BApXcRwYxKPVC9q4Q8kfutLLJaXe7WP5R0yUPtuNy9xJwMjcZnYM0uto",
#     "unionwsws": "{\"devicefinger\":\"eidAc9dc81217dseqd38gCK7TbKIiL6Cm1\\/1sand\\/gOCTtW3ixPBxFenrBKQP\\/Dhkx1O3jUyW0cSugwTpxSVZNkYmh625wF9Eg35XO4KdDPBrbLW65lJ\",\"jmafinger\":\"JD012145b9JRG2W4U4Q417187121116600670W-_joxxqQa_R-6v46UFiijYmgl1Iqh5ez_k5PGWQzUuRCq8ohiG9jWJCIqkPL1kL6t-8dWo_11h_A2PNOYtg0tvjldk~BApXcRwYxKPVC9q4Q8kfutLLJaXe7WP5R0yUPtuNy9xJwMjcZnYM0uto\"}"
# }
url = "https://api.m.jd.com/client.action"
params = {
    "functionId": "cartAdd",
    "clientVersion": "12.3.1",
    "build": "99032",
    "client": "android",
    "partner": "jingdong",
    "oaid": "f5a4c6cf27afe43f",
    "sdkVersion": "28",
    "lang": "zh_CN",
    "harmonyOs": "0",
    "networkType": "UNKNOWN",
    "uemps": "0-0-0",
    "ext": "{\"prstate\":\"0\",\"pvcStu\":\"1\",\"cfgExt\":\"{\\\"privacyOffline\\\":\\\"0\\\"}\"}",
    "eid": "eidA956e812095s7LZ5D7hlMTqaKB5eZ2zAKPi2eRX5YUqf9Grx45MGWtGQyDX6+FPuz01p1JS2KwC5+rDzlGtQ64IdwlsmmgI3oNz+1NAxL9TDaK8E3",
    "ef": "1",
    "ep": "{\"hdid\":\"JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=\",\"ts\":1718961064527,\"ridx\":-1,\"cipher\":{\"d_brand\":\"IPVLV0VT\",\"screen\":\"CJuyCMenCNqm\",\"area\":\"CV83Cv8yDzu5XzK=\",\"uuid\":\"ZtVrDQC2Y2YyD2PwZJGzZq==\",\"osVersion\":\"Dy4nBtS=\",\"wifiBssid\":\"dW5hbw93bq==\",\"d_model\":\"IO1LBUPCCNK=\",\"aid\":\"ZtVrDQC2Y2YyD2PwZJGzZq==\"},\"ciphertype\":5,\"version\":\"1.2.0\",\"appname\":\"com.jingdong.app.mall\"}",
    "bef": "1",
}
from urllib.parse import urlencode, urljoin
import json

import time

decrypt_body = '{"addressId":"6003870953","appleCare":0,"businessId":"","businessName":"PD_addCart","cartBundleVersion":"12301","cartuuid":"34b10441-8144-4d1f-8fa2-9548437a1102","configVersion":0,"coord_type":"","cvhv":"145626563648","degradation":0,"hitNewUIStatus":0,"homeWishListUserFlag":"3","latitude":"","longitude":"","mqTriggerStatus":"0","noResponse":true,"operations":[{"TheSkus":[{"Id":"100088695022","num":"1"}],"carttype":"2"}],"syntype":"1","userType":"1"}'
#decrypt_body = '{"addressId":"6003870953","appleCare":0,"businessId":"","cartBundleVersion":"12301","cartRequestType":13,"cartuuid":"34b10441-8144-4d1f-8fa2-9548437a1102","configVersion":249,"coord_type":"","cvhv":"145626563648","degradation":0,"filterTag":"6666","hasSearchParam":false,"hitNewUIStatus":0,"homeWishListUserFlag":"3","latitude":"","longitude":"","mqTriggerStatus":"0","page":1,"syntype":"1","tabMenuValue":"","updateTag":true,"userType":"1"}'

data = {
    "body": '{"hdid":"JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=","ts":1718961121210,"ridx":-1,"cipher":{"body":"%s"},"ciphertype":5,"version":"1.2.0","appname":"com.jingdong.app.mall"}' % getbody(
        decrypt_body, True)
}
timess = str(int(time.time() * 1000))
# logger.debug(body_data)

body_data = json.dumps(decrypt_body, separators=(',', ':'), ensure_ascii=False)

sign = getSign(params["functionId"], decrypt_body.encode().decode(), 'android', params['clientVersion'],
               'f5a4c6cf27afe43f', timess)

params = {**params, **sign}
query_string = urlencode(params)
full_url = urljoin(url, '?' + query_string)
logger.debug(full_url)

jdgs_data = {
    "uri": full_url,
    "body": decrypt_body,
    "eid": params["eid"],
    "bef": False,
    "appver": "12.3.1",
    "code": '1a6dfafe1e96da0742973abc3984e2'
}

# jdgs_response = requests.post(jdgs_url, json=jdgs_data).json()
# logger.info(jdgs_response)
jdgs_result = jdgsSign(url=jdgs_data['uri'], body=decrypt_body, eid=jdgs_data['eid'], appver='12.3.1')
headers['jdgs'] = json.dumps(jdgs_result)
response = sess.post(url, headers=headers, params=params, data=data)
logger.info(response.text[:500])
